#include <iostream>
#include <pthread.h>
#include <unistd.h>


const int thread_num = 3;

pthread_mutex_t mutex;
pthread_cond_t cond;


int data = 0; // 共享资源

void* thread_work(void* argc)
{
    int* num = (int*)argc;
    pthread_mutex_lock(&mutex);
    printf("sub_thread[%d] has been created successfully\n", *num);

    while (data == 0) // 主线程将data修改为1之前，所有子线程都在循环等待条件变量的信号
    {
        printf("sub_thread[%d] is waiting for data\n", *num);
        pthread_cond_wait(&cond, &mutex); // 释放互斥锁
    }

    printf("sub_thread[%d] wake up\n", *num);
    
    pthread_mutex_unlock(&mutex);
    return nullptr;
}


int main()
{
    pthread_t threads[thread_num];

    pthread_mutex_init(&mutex, nullptr);
    pthread_cond_init(&cond, nullptr);

    for (int i = 0; i < thread_num; i++)
    {
        int* num = new int(i);
        int ret = pthread_create(&threads[i], nullptr, thread_work, num);
        if (ret != 0)
        {
            std::cout << "pthread create error" << std::endl;
        }
    }


    sleep(2);
    std::cout << "main thread is going to wake up all sub_threads" << std::endl;
    
    pthread_mutex_lock(&mutex);
    data = 1; // 主线程修改data
    pthread_cond_broadcast(&cond);
    pthread_mutex_unlock(&mutex);

    for (int i = 0; i < thread_num; i++)
    {
        pthread_join(threads[i], nullptr);
    }

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    return 0;
}